//
//  SportReportContainerViewController.m
//  CoolTennisBall
//
//  Created by 谢伟康 on 15/12/18.
//  Copyright © 2015年 CoolLang. All rights reserved.
//

#import "SportReportContainerViewController.h"
#import "SportReportViewController.h"
#import "SportSkillViewController.h"
#import "UIImage+ImageFromView.h"
#import "NSBundle+CurrentLanguage.h"
#import "CoollangTennisBall-Swift.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "NSString+Extension.h"
#import "SportSkillShareController.h"
#import "SportReportShareController.h"

@interface SportReportContainerViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UISegmentedControl *reportSegmentedControl;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) SportDetailReportModel *detailReportModel;
@end

@implementation SportReportContainerViewController
{
    __weak SportReportViewController * _sportReportVC;
    __weak SportSkillViewController * _sportSkillVC;
}

#pragma mark - ViewLifeCircle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureNav];
    [self configureLocalization];
    [self sendRequestGetDetailSport];
    
    self.scrollView.delaysContentTouches = NO;
    self.scrollView.canCancelContentTouches = YES;
}


#pragma mark - Localization
- (void)configureLocalization {
    [self.reportSegmentedControl setTitle:NSLocalizedString(@"Report", nil)forSegmentAtIndex:0];
    [self.reportSegmentedControl setTitle:NSLocalizedString(@"Analysis", nil) forSegmentAtIndex:1];
}

#pragma mark - IBAction
- (IBAction)chooseReportMode:(UISegmentedControl *)sender {
    
    self.scrollView.contentOffset = CGPointMake(sender.selectedSegmentIndex *self.scrollView.frame.size.width, 0);
    if (sender.selectedSegmentIndex == 1) {
        [_sportSkillVC updateUI];
    }
}

#pragma mark - Nav

- (void)configureNav
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sport_icon_blackbackArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Share", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickToShare)];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickToShare
{
    [self performSegueWithIdentifier:@"ShareSegue" sender:nil];
}


#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"SportSkill"]) {
        _sportSkillVC = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:@"SportReport"]){
        _sportReportVC = segue.destinationViewController;
    } else if ([segue.identifier isEqualToString:@"ShareSegue"]) {
        ShareAppViewController *controller = (ShareAppViewController *)segue.destinationViewController;
        controller.detailReportModel = self.detailReportModel;
        controller.shareControllerType = _reportSegmentedControl.selectedSegmentIndex;
        controller.dayTimeStamp = self.selectedDayTimeStamp;
        controller.showHud = ^{
           MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
           [hud hide:true afterDelay:2];
        };
    }
}

#pragma mark - Private Method

- (void)sendRequestGetDetailSport
{
    // 1.先判断本地是否有数据
    if (self.recordItem.isSyncDetailReportData && self.recordItem.reportDetailLnaguage == [NSBundle currentLangeuage]) {
        SportDetailReportModel * model = [[SportDetailReportModel alloc] init];
        [model configureModelWithDic:[NSString dictionaryWithJsonString:self.recordItem.detailReportInfo]];
        self.detailReportModel = model;
        NSInteger totalCount = self.detailReportModel.pingJiCount + self.detailReportModel.xuanQiuCount + self.detailReportModel.xueQiuCount + self.detailReportModel.jieJiCount + self.detailReportModel.kouShaCount + self.detailReportModel.faQiuCount;
        if (self.detailReportModel.detailDesArray.count < 1 || totalCount == 0) {
            // 重新请求网络数据
             [self requestGetSportDetailData];
        }else {
            [_sportReportVC configureUI:self.detailReportModel];
            _sportSkillVC.selectedDayTimeStamp = self.selectedDayTimeStamp;
            _sportSkillVC.detailReportModel = self.detailReportModel;
        }
    }else {
        [self requestGetSportDetailData];
    }
}

- (void)requestGetSportDetailData {
    // 2.没有再请求数据
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    YFStatisticsApi *detailApi = [YFStatisticsApi getSportDetailReportWithSportDateString:self.dateString];
    
    [[YFNetworkingService sharedInstance] sendRequest:detailApi callback:^(BOOL success, id result, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@",detailApi.responseInfo);
        if (success) {
            SportDetailReportModel * model = [[SportDetailReportModel alloc] init];
            [model configureModelWithDic:[detailApi.responseObject objectForKey:@"errDesc"]];
            NSString *responseInfoJosnStr = [NSString dictionaryToJson:[result responseInfo]];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            
            if (responseInfoJosnStr != nil) {
                self.recordItem.detailReportInfo = responseInfoJosnStr;
                self.recordItem.isSyncDetailReportData = YES;
                self.recordItem.reportDetailLnaguage = [NSBundle currentLangeuage];
            }
            [[RLMRealm defaultRealm] commitWriteTransaction];
            self.detailReportModel = model;
            [_sportReportVC configureUI:self.detailReportModel];
            _sportSkillVC.selectedDayTimeStamp = self.selectedDayTimeStamp;
            _sportSkillVC.detailReportModel = self.detailReportModel;
        }else{
            [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Unable to get the report", nil) afterDelay:1.5];
        }
    }];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.page = scrollView.contentOffset.x/scrollView.frame.size.width;
    self.reportSegmentedControl.selectedSegmentIndex = self.page;
    if (self.page == 1) {
        [_sportSkillVC updateUI];
    }
}

@end
